import rclpy
from rclpy.node import Node
from turtlesim.srv import Spawn
class Exer01SpawnPy(Node):
    def __init__(self):
        super().__init__("exer01_spawn_py_node")
        self.declare_parameter("x",3.5)
        self.declare_parameter("y",3.5)
        self.declare_parameter("theta",0.0)
        self.declare_parameter("turtle_name","turtle2")  
        self.get_parameter("x") .get_parameter_value().double_value  #把参数x的值赋予属性x
        self.y=self.get_parameter("y").get_parameter_value().double_value
        self.theta=self.get_parameter("theta").get_parameter_value().double_value
        self.turtle_name=self.get_parameter("turtle_name").get_parameter_value().string_value
        # p1=rclpy.Parameter("x",value=3.5)
        # p2=rclpy.Parameter("y",value=3.5)
        # p3=rclpy.Parameter("theta",value=3.14)
        # p4=rclpy.Parameter("turtle_name",value="turtle2")
        # self.x=p1.value
        # self.y=p2.value
        # self.theta=p3.value
        # self.turtle_name=p4.value  这种写法在launch文件没法传参 已经写死

        self.client=self.create_client(Spawn,"spawn")

        while not self.client.wait_for_service(1.0):
            self.get_logger().info("服务连接中")
    
    def request(self):
        request=Spawn.Request()
        request.x=self.x
        request.y=self.y
        request.theta=self.theta
        request.name=self.turtle_name

        self.future=self.client.call_async(request) 
        #返回一个future对象，不用一直守在那里等商家回复（服务响应）。

def main():
    rclpy.init()
    spawn=Exer01SpawnPy()
    spawn.request()
    rclpy.spin_until_future_complete(spawn,spawn.future)
    response=spawn.future.result()
    if len(response.name)==0:
        spawn.get_logger().info("乌龟重名了")
    else:
        spawn.get_logger().info("乌龟生成了")
    rclpy.shutdown()
if __name__=='__main__':
    main()            
